package copyengine.ui.component.scrollablePanel.list
{
    import copyengine.ui.component.scrollablePanel.element.ICEScrollableElement;
    import copyengine.ui.component.scrollablePanel.element.list.ICEListElement;
    import copyengine.ui.component.scrollablePanel.scrollPanel.CEScrollPanelUtils;
    import copyengine.utils.GeneralUtils;

    /**
     * CEList的帮助类.  ScrollPanel和List的设计思路是 让两个类(CEScrollPanel CEList)尽量简单
     * 而上层逻辑 方便使用的函数 全部封装到在该类内部
     */
    public class CEListUtils
    {
        public function CEListUtils()
        {
        }

        public static function linkElementToList(_e:ICEListElement, _list:CEList, _data:*):void
        {
            _e.scrollPanel = _list;
            _e.renderData = _data;
            _e.displayContainerSharePool = _list.elementDisplayContainerSharePool;
        }

        /**
         * 在CEList初始化或者Element发生变化以后 调用该函数对CEList进行一次强制刷新
         */
        public static function forceRefresh(_list:CEList):void
        {
            CEScrollPanelUtils.forceRefresh(_list);
        }

        public static function refreshDataProvider(_list:CEList, _dataArray:*, _elementCreateFunction:Function):void
        {
            var allNewElementVector:Vector.<ICEListElement> = new Vector.<ICEListElement>();
            var length:int = _dataArray.length;
            for (var i:int = 0; i < length; i++) {
                var newElement:ICEListElement = getElement(_list.allElementVector, _elementCreateFunction);
                newElement.sortRank = i;
                newElement.renderData = _dataArray[i];
                newElement.displayContainerSharePool = _list.elementDisplayContainerSharePool;
                allNewElementVector.push(newElement);
            }

            //如果List中还有剩余Element清除掉
            GeneralUtils.disposeAllDisposeAbleObjectInArrayOrVector(_list.allElementVector);
            //将新的Element 重新Push进来
            for each(var element:ICEListElement in allNewElementVector) {
                _list.addElement(element);
            }
        }

        private static function getElement(_oldAllElementVector:Vector.<ICEScrollableElement>, _elementCreateFunction:Function):ICEListElement
        {
            if (_oldAllElementVector.length > 0) {
                var element:ICEScrollableElement = _oldAllElementVector.pop();
                element.hide();
                return element as ICEListElement;
            } else {
                return _elementCreateFunction();
            }
        }

    }
}
